//index.js
var util = require('../../utils/util.js')
//获取应用实例
var app = getApp()
Page({
  data: {
    fChoosedPicture: false,
    fShowForwardImage: false,

    backwardUrl: undefined, // 背景图像
    forwardUrl: undefined, // 前景图像，生成的图像
    templateList: [
    ],
  },

  backwardImageData: null,
  forwardImageDataList: [], // 储存API 返回的图片, 避免重复的调用
  forwardImagTempUrl: undefined, //用于保存本地的临时url
  forwardImagUrlList: [], //用于保存本地的临时url 的列表
  currentOption: null, // 当前模板选择

  onLoad: function () {
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      })
    })
    this.data.templateList[0].selected = true;

  },


  callBaiduApi: function (option) {
    var self = this
    var global = app.globalData

    const MSG = function (msg, type, delay) {
      var type = type || 'none'
      if (delay && delay > 0) {
        setTimeout(() => {
          wx.showToast({
            title: msg,
            icon: type,
            duration: 2000
          })
        }, delay)
      } else {
        wx.showToast({
          title: msg,
          icon: type,
          duration: 3000
        })
      }
    }
    var templateData
    // TODE: 模板Base64获取

    var onLoading = true
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/face/v1/merge',
      method: 'POST',
      data: {
        access_token: global.token,
        image_type: 'BASE64',
        image_template: templateData,
        image_target: self.backwardImageData,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: (res) => {
        var data = res.data
        // console.log(data)
        if (typeof (data) != 'object') {
          try {
            data = JSON.parse(data)
          } catch (e) {
            console.log(e)
            data = false
            MSG('数据解析错误', 'none', 200)
          }
        }
        if (!data) {
          return
        }
        var errorCode = data.error_code
        if (typeof (errorCode) == 'undefined') {
          MSG('请求错误', 'none', 200)
        } else if (errorCode > 0) {
          MSG(data.error_msg, 'none', 200)
          console.log('调用错误:', data.error_msg)
        } else {
          var imgData = data.result.merge_image
          if (imgData) {
            self.forwardImageDataList[option.id] = imgData
            if (onLoading) {
              self.showForwardImage(true, option)
            }
          }
        }

      },
      fail: (res) => {
        console.log(res)
        MSG('发起请求失败', 'none', 200)
      },
      complete: () => {
        if (onLoading) {
          wx.hideLoading()
        }
      }
    })

    setTimeout(() => {
      onLoading = false
      wx.hideLoading()
      MSG('请求超时', 'none')
    }, 5000)
  },

  /**
   * 选择模板图像
   */
  onSelectTemplateItem: function (event) {
    console.log('选择');
    var self = this
    var global = app.globalData
    if (!self.data.backwardUrl) {
      wx.showToast({
        title: '请先选择一张图片',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (!global.token) {
      console.log('无效的Token')
      return
    }
    //console.log(event)
    var id = parseInt(event.currentTarget.dataset.index) || 0
    var option = self.data.templateList[id]
    //var option  = event.currentTarget.dataset.selected

    if (option == self.currentOption) {
      self.showForwardImage(false)
      return
    }
    if (self.forwardImageDataList[option.id]) {
      self.showForwardImage(true, option)
    }
    else {
      console.log("发起请求", option)
      self.callBaiduApi(option)
    }
  },

    
	/**
	 * 格式化 前景图和背景图 Image 的大小
	 * @param {object} detail 
	 */
	formatImageTagSize(width, height){
		const MAX_WIDTH = 750
		const MAX_HEIGHT = 1000

		width = width / this.deviceRatio
		height = height / this.deviceRatio
		// 限制宽高
		width = width > MAX_WIDTH ? MAX_WIDTH : width
		height = height > MAX_HEIGHT ? MAX_HEIGHT : height
		this.setData({
			previewImageTagWidth: width,
			previewImageTagHeight: height
		})
  },

  	/**
	 * 显示前景图像, API处理后的图像,并隐藏背景图像
	 * @param {boolean} show 
	 * @param {object} option 
	 */
	showForwardImage:function(show, option){
		var self = this
		if(self.currentOption != null){
			self.currentOption.selected = false
		}
		if(show){
			option.selected = true
			self.setData({
				fShowForwardImage: true,
				forwardUrl: this.forwardImageDataList[option.id],
				optionList: this.data.optionList
			})
			self.currentOption = option
		}
		else{
			self.setData({
				fShowForwardImage: false,
				optionList: this.data.optionList
			})
			self.currentOption = null
			self.forwardImagTempUrl = undefined
		}
	},

  /**
   * 背景图片加载
   */
  onTemplateImageLoad: function () {

  },


  
  /**
   * 选择相册
   * \
   */
  onTouchSelectAlbum: function () {
    var self = this
    // 打开系统相册
    wx.chooseImage({
      count: 6, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePath = res.tempFilePaths[0]
        console.log('选择的图像路劲:', tempFilePath)
        self.setData({
          backwardUrl: tempFilePath,
        })
      },
      complete: function () {
        console.log('完成')
      }
    })

  },

  /**
   * 提交合成
   */
  onTouchSubmit: function () {
    var self = this
    wx.showToast({ // 显示Toast
      title: '成功',
      icon: 'success',
      duration: 1500,
      mask: false
    })
    setTimeout(function () {
      wx.navigateTo({
        url: '../editor/editor?url=' + self.data.backwardUrl,
      })
    }, 2000);
  },

},
)
